#coding: utf8

import sys
import os.path 

cur_path = os.path.dirname(__file__)
parent_path = os.path.abspath(os.path.join(cur_path, '..'))
sys.path.append(parent_path)

from gevent import server,pool,spawn,monkey
monkey.patch_all()

import time
import pymongo
import redis

import json
import logging
import logging.config

from exceptions import Exception

import items
import trades

logging.config.fileConfig('./conf/log.conf')
rlog = logging.getLogger('root')

def traderate_content_filter(content):
    w = 0
    if u'系统默认好评' in content:
        w += 1000 
    if u'一般' in content:
        w += 100 
    if len(content) < 6:
        w += 500
    return w

def traderate_reclist_resort(rec_list):
    for tr in rec_list:
        w  = 10000
#for time weight
        try:
            tw = time.strptime(tr['created'], '%Y-%m-%d %H:%M:%S' ) #2011-10-17 21:38:51)
            tw = time.mktime(tw) 
            tw = 1 + (time.time() - tw) / 3600 # days from list items
        except:
            tw = 1000 
        w -= tw
#for text length weight
        w += len(tr['content']) * 10
#for text content weight 
        w -= traderate_content_filter(tr['content'])

        tr['weight'] = w
    sort_by_wegiht = lambda x, y: cmp(x['weight'], y['weight'])
    rec_list.sort(cmp=sort_by_wegiht, reverse=True)

def gen_traderate_rec(nick, mdb, rdb, num_iid):
    res = rdb.smembers('orders:'+str(num_iid))
    rec_list = []
    rate_num = 0
    for oid in res:
        tr = mdb.traderate.find_one({'_id':int(oid)})
        if not tr:
            continue
        rate_num += 1
        if tr['result'] != 'good':
            continue
        rec_list.append(tr)
    if rate_num == 0:
        return (0, [])
    #resort rec_list
    traderate_reclist_resort(rec_list) 
    return (rate_num, [ i['_id'] for i in rec_list[:10] ])


def shop_rec(nick, mdb, rdb):
    rdb.delete(nick, 'ordernum:'+nick)
    items.items_rec(nick, mdb, rdb)
    trades.trades_rec(nick, mdb, rdb)
    res = rdb.zrange(nick, 0, 25, desc=True, withscores=True)
    shop_rec_list = []
    for num_iid, score  in res:
        rate_num, traderates = gen_traderate_rec(nick, mdb, rdb, num_iid)
#rdb.hincrby('ordernum:'+trade['seller_nick'], str(order['num_iid']), int(order['num']))
        order_num = rdb.hget('ordernum:'+nick, str(num_iid))
        if not order_num:
            order_num = 0
        d = {
                'num_iid':int(num_iid),
                'score':score,
                'rate_num': rate_num,
                'rates': traderates,
                'trade_num':order_num,
        }
        shop_rec_list.append(d)
    mdb.shop_rec.save({'_id':nick, 'recs':shop_rec_list})


def testing_shop_rec(nick):
    m = pymongo.Connection(port=57324)
    rdb = redis.StrictRedis(host='127.0.0.1', port=56379, db=11)
    shop_rec(nick, m.taogold, rdb)
    rec = m.taogold.shop_rec.find_one({'_id':nick})
    import pprint
    pprint.pprint(rec)

def spawn_shop_rec(nick):
    rlog.info('recommander processing for nick: %s' %(repr(nick)))
    m = pymongo.Connection(port=57324)
    rdb = redis.StrictRedis(host='127.0.0.1', port=56379, db=11)
    shop_rec(nick, m.taogold, rdb)

def srv_handle(socket, address):
    ct = socket.recv(1024)
    while not ct.endswith('\n\n'):
        ct += socket.recv(1024)
    try:
        u = json.loads(ct)
    except Exception as e:
        rlog.warning('parse json[%s] fail: %s' %(repr(ct), repr(e)))
        socket.send('fail\n\n')
        socket.close()
        return
    if 'nick' not in u:
        rlog.warning('wrong data: %s' %(repr(ct)))
        socket.send('fail\n\n')
    else:
        spawn(spawn_shop_rec, u['nick'])
        socket.send('success\n\n')
    socket.close()

def srv():
    srv = server.StreamServer(('127.0.0.1', 8400), srv_handle)
    srv.serve_forever()

def main():
    try:
        pid = os.fork() 
        if pid>0:
            sys.exit(0)
    except Exception as e:
        sys.exit('fork #1 error: %s' %(str(e)))
    try:
        pid = os.fork() 
        if pid>0: 
            sys.exit(0)
    except Exception as e:
        sys.exit('fork #2 error: %s' %(str(e)))
    srv()

if __name__ == '__main__':
    #testing_shop_rec('miaowanghuan')
    #testing_shop_rec('古代')
    main()





